
//声明 reducer 函数
let countReducer = (state=5201314, action) => {
  // console.log(state);
  //回调函数(reducer 函数)执行时机: 当store对象在创建以及在更新状态时, 会自动执行
  switch(action.type){
    case 'add':
      return state + action.payload;
    case 'sub':
      return state - action.payload;
    case 'times':
      return state * action.payload;
    //default 非常关键, 一定要返回 state, 否则创建的初始值将变为 undefined
    default: 
      return state;
  }
}

//暴露
export default countReducer;

//封装函数 (同步的 action creator 『action的创造器』)
export let addAction = (payload) => {
  return {type: 'add', payload: payload};
}
export let subAction = payload => ({type: 'sub', payload});
export let timesAction = payload => ({type: 'times', payload});

//声明一个函数 『异步的 action creator』
export let asyncAddAction = payload => {
  //异步的 action 函数可以写一个形参, 来接收 dispatch 函数
  return dispatch => {
    setTimeout(() => {
      dispatch(addAction(payload));
    }, 1000);
  }
}

